package com.example.a2306_shop.fg

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.a2306_shop.R
import com.example.a2306_shop.adapter.CouponAdapter
import com.example.a2306_shop.adapter.MenuAdapter
import com.example.a2306_shop.adapter.ProductAdapter
import com.example.a2306_shop.adapter.TypeAdapter
import com.example.a2306_shop.databinding.FragmentHomeBinding
import com.example.lib_base.mvvm.BaseFragment
import com.example.lib_base.room.AppDbUtils
import com.example.lib_base.room.HistoryEntity
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.google.android.material.chip.Chip
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener


class HomeFragment : BaseFragment<FragmentHomeBinding,HomeViewModel>() {
    val imgs = mutableListOf<String>()//用来存放轮播图地址
    lateinit var menuAdapter: MenuAdapter
    lateinit var typeAdapter: TypeAdapter

    lateinit var productAdapter: ProductAdapter
    var type = 4//当前分类未4  因为第一个的type为4
    var page = 1//当前页面
    var limit = 5//每页显示5条，因为总数据只有8个，不然无法看到刷新加载的效果

    lateinit var couponAdapter: CouponAdapter
    override fun initData() {
        viewModel.indexSuccess.observe(this){
            if(it.code==200){
                //轮播图--数据绑定的形式  +绑定适配器
                it.data.banner.forEach {
                    imgs.add(it.pic)
                }
                binding.imgs = imgs
                //菜单
                menuAdapter.data.clear()
                menuAdapter.data.addAll(it.data.menus)
                menuAdapter.notifyDataSetChanged()
                //分类
                typeAdapter.data.clear()
                typeAdapter.data.addAll(it.data.explosiveMoney)
                typeAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.indexProductSuccess.observe(this){
            if(it.code==200){
                binding.smart.finishRefresh()
                binding.smart.finishLoadMore()
                if(page==1){
                    productAdapter.data.clear()
                }
                productAdapter.data.addAll(it.data.list)
                productAdapter.notifyDataSetChanged()
                //当没有请求到其他数据后，给出友好提示
                if(it.data.list.size==0){
                    ToastUtils.showLong("没有更多数据啦，查看其他的吧")
                }
            }
        }

        viewModel.couponSuccess.observe(this){
            if(it.code==200){
                couponAdapter.data.clear()
                couponAdapter.data.addAll(it.data)
                couponAdapter.notifyDataSetChanged()
            }
        }
        viewModel.receiveSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.receiveFail.observe(this){
            ToastUtils.showLong(it)
        }

    }

    override fun initView() {
        //初始化菜单
        menuAdapter = MenuAdapter()
        binding.rvMenu.adapter = menuAdapter
        binding.rvMenu.layoutManager = GridLayoutManager(context,5)
        //初始化分类
        typeAdapter = TypeAdapter()
        binding.rvType.adapter = typeAdapter
        binding.rvType.layoutManager = GridLayoutManager(context,4)
        //请求首页数据
        viewModel.index()
        //初始化商品列表
        productAdapter = ProductAdapter()
        binding.rvProduct.adapter =productAdapter
        binding.rvProduct.layoutManager = GridLayoutManager(context,2)

        viewModel.indexProduct(type, limit, page)

        //点击分类 商品列表发生变化
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            type = typeAdapter.data[position].type.toInt()
            page = 1
            typeAdapter.setType(type)
            viewModel.indexProduct(type, limit, page)
        }
        //刷新加载更多
        binding.smart.setOnRefreshLoadMoreListener(object:OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                viewModel.indexProduct(type, limit, page)

            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                viewModel.indexProduct(type, limit, page)
            }
        })

        //初始化优惠券列表
        couponAdapter = CouponAdapter()
        binding.rvCoupon.adapter = couponAdapter
        binding.rvCoupon.layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false)
        //请求优惠券列表
        viewModel.coupon("10","1","1")
        //点击领取优惠券
        couponAdapter.setOnItemClickListener { adapter, view, position ->
            //判断当前是否已经登录  未登录跳转到登录界面  已登录 可以进行领取操作
            if(SPUtils.getInstance().getString("token").isEmpty()){
                ARouter.getInstance().build("/user/LoginActivity").navigation()
            }else{
                //判断当前优惠券的状态  已领取   直接吐司  未领取  调用接口进行领取
                if(couponAdapter.data[position].isUse){
                    ToastUtils.showLong("优惠券只能领取一次，不能重复领取")
                }else{
                    viewModel.couponReceive(couponAdapter.data[position].id)
                    //局部刷新 减少交互
                    couponAdapter.data[position].isUse = true
                    (couponAdapter.getViewByPosition(position,R.id.coupon_status) as TextView).text = "已领取"
                }

            }
        }
        //点击菜单，跳转到对应界面
        menuAdapter.setOnItemClickListener { adapter, view, position ->
            when (position){
                //点击的是第八个菜单  地址管理
                7-> ARouter.getInstance().build("/app/AddressActivity").navigation()
                0->{
                    val addressPicker = AddressPicker(requireActivity())
                    addressPicker.setTitle("请选择配送地址")
                    addressPicker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
                    addressPicker.setOnAddressPickedListener { province, city, county ->
                        ToastUtils.showLong("${province.name}${city.name}${county.name}")
                    }
                    addressPicker.show()
                }
            }
        }
       /* //点击搜索框，跳转到搜索界面
        binding.tvKeyword.setOnClickListener {
            ARouter.getInstance().build("/app/SearchActivity").navigation()
        }*/
        //点击商品列表，跳转到详情界面
        productAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/DetailActivity").withInt("pid",productAdapter.data[position].id).navigation()
        }
        binding.sv.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                if(query!=null){
                    viewModel.search(query,10,1)
                    AppDbUtils.getAppDb().getHistoryDao().insert(HistoryEntity(query))
                    queryHis()
                }
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return true
            }
        })
        queryHis()//进入界面就查询

    }

    private fun queryHis() {
        val query = AppDbUtils.getAppDb().getHistoryDao().query()
        if(query.size!=0){
            //先清空原来的历史记录，重新加载
            binding.cg.removeAllViews()
            query.forEach {
                //创建 chip控件  给chip的tv进行赋值   将chip 添加到chipGroup中
                val chip =
                    LayoutInflater.from(context).inflate(R.layout.item_chip_home, null) as Chip

                chip.findViewById<TextView>(R.id.tv).text = it.keyword

                binding.cg.addView(chip)

                //点击再次查询
                chip.setOnClickListener {it1->

                    binding.sv.setQuery(it.keyword,true)
                }

                //删除
                chip.setOnCloseIconClickListener {it2->
                    AppDbUtils.getAppDb().getHistoryDao().delete(it)
                    binding.cg.removeView(it2)
                }
            }
        }
    }

    override fun getViewModel(): Class<HomeViewModel>  = HomeViewModel::class.java

    override fun getLayout(): Int = R.layout.fragment_home

}